/**
 * 
 */
package com.mbengue.corp.apr.ra.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.mbengue.corp.apr.ra.core.Article;
import com.mbengue.corp.apr.ra.core.Image;
import com.mbengue.corp.apr.ra.dao.ImageDao;
import com.mbengue.corp.apr.ra.util.HibernateUtil;

/**
 * @author MMB11447
 *
 */
public class ImageDaoImpl implements Serializable, ImageDao {

	private static final long serialVersionUID = 1L;
	private Session session;
	
	public ImageDaoImpl() {
		session = HibernateUtil.getSessionFactory();
	}

	/* (non-Javadoc)
	 * @see com.mbengue.corp.apr.ra.dao.ImageDao#ajouterImage(com.mbengue.corp.apr.ra.core.Image)
	 */
	public void ajouterImage(Image image) throws HibernateException {
		Transaction transaction = session.beginTransaction();
		try {
			session.save(image);
			transaction.commit();
		} catch (Exception e) {
			transaction.rollback();
			throw new HibernateException(e);
		} finally {
			session.flush();
			session.close();
		}
	}

	/* (non-Javadoc)
	 * @see com.mbengue.corp.apr.ra.dao.ImageDao#modifierImage(com.mbengue.corp.apr.ra.core.Image)
	 */
	public void modifierImage(Image image) throws HibernateException {
		Transaction transaction = session.beginTransaction();
		try {
			session.update(image);
			transaction.commit();
		} catch (Exception e) {
			transaction.rollback();
			throw new HibernateException(e);
		} finally {
			session.flush();
			session.close();
		}
	}

	/* (non-Javadoc)
	 * @see com.mbengue.corp.apr.ra.dao.ImageDao#trouverImage(java.lang.String)
	 */
	public Image trouverImage(String nom) throws HibernateException {
		Criteria criteria = session.createCriteria(Article.class);
		criteria.add(Restrictions.eq("nom", nom));
		
		return (Image) criteria.uniqueResult();
	}

	/* (non-Javadoc)
	 * @see com.mbengue.corp.apr.ra.dao.ImageDao#lesImagesD1Article(com.mbengue.corp.apr.ra.core.Article)
	 */
	@SuppressWarnings("unchecked")
	public List<Image> lesImagesD1Article(Article article) throws HibernateException {
		Criteria criteria = session.createCriteria(Article.class);
		criteria.add(Restrictions.eq("article", article.getTitre()));
		
		return criteria.list();
	}

	/* (non-Javadoc)
	 * @see com.mbengue.corp.apr.ra.dao.ImageDao#supprimerImage(java.lang.String)
	 */
	public void supprimerImage(String nom) throws HibernateException {
		Image image = trouverImage(nom);
		
		if(image == null) {
			return;
		}
		
		Transaction transaction = session.beginTransaction();
		try {
			session.delete(image);
			transaction.commit();
		} catch (Exception e) {
			transaction.rollback();
			throw new HibernateException(e);
		} finally {
			session.flush();
			session.close();
		}
	}

}
